<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模型名称" prop="modelName">
        <el-input v-model="queryParams.modelName" placeholder="请输入模型名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['tool:llm:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['tool:llm:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['tool:llm:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['tool:llm:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="llmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="场景代码" align="center" prop="scenario" />
      <el-table-column label="模型名称" align="center" prop="modelName" />
      <el-table-column label="模型描述" align="center" prop="modelDesc" />
      <el-table-column label="是否启用" align="center" prop="used">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.used" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #header>
          <el-button text type="danger" icon="Connection" @click="handleCach" v-hasPermi="['tool:llm:edit']">生效修改</el-button>
        </template>
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['tool:llm:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['tool:llm:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改大模型配置对话框 -->
    <el-drawer :title="title" v-model="open" size="800px" append-to-body>
      <el-form ref="llmRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="renderField(true, true)" label="场景代码" prop="scenario">
          <el-input v-model="form.scenario" placeholder="请输入场景代码" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="模型名称" prop="modelName">
          <el-input v-model="form.modelName" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="模型描述" prop="modelDesc">
          <el-input v-model="form.modelDesc" placeholder="请输入模型描述" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="API_KEY" prop="apiKey">
          <el-input v-model="form.apiKey" placeholder="请输入API_KEY" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="BASE_URL" prop="baseUrl">
          <el-input v-model="form.baseUrl" placeholder="请输入BASE_URL" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="系统提示词" prop="systemPrompt">
          <el-input v-model="form.systemPrompt" type="textarea" rows="6" placeholder="请输入系统提示词" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="用户提示词" prop="userPrompt">
          <el-input v-model="form.userPrompt" type="textarea" rows="6" placeholder="请输入用户提示词" />
        </el-form-item>
        <el-form-item v-if="renderField(true, true)" label="是否启用" prop="used">
          <el-radio-group v-model="form.used">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="parseInt(dict.value)">
              {{ dict.label }} </el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Llm">
import { listLlm, getLlm, delLlm, addLlm, updateLlm, cachLlm } from "@/api/tool/llm";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');
console.log("sys_normal_disable", sys_normal_disable)

const llmList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    modelName: null,
  },
  rules: {
    scenario: [
      { required: true, message: "场景代码不能为空", trigger: "blur" }
    ],
    modelName: [
      { required: true, message: "模型名称不能为空", trigger: "blur" }
    ],
    apiKey: [
      { required: true, message: "API_KEY不能为空", trigger: "blur" }
    ],
    baseUrl: [
      { required: true, message: "BASE_URL不能为空", trigger: "blur" }
    ],
    systemPrompt: [
      { required: true, message: "系统提示词不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询大模型配置列表 */
function getList() {
  loading.value = true;
  listLlm(queryParams.value).then(response => {
    llmList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    modelName: null,
    modelDesc: null,
    apiKey: null,
    baseUrl: null,
    systemPrompt: null,
    used: null,
  };
  proxy.resetForm("llmRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加大模型配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLlm(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改大模型配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["llmRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateLlm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功，点击 \"生效修改\" 才正式生效！");
          open.value = false;
          getList();
        });
      } else {
        addLlm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功，点击 \"生效修改\" 才正式生效！");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除大模型配置编号为"' + _ids + '"的数据项？').then(function () {
    return delLlm(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('tool/llm/export', {
    ...queryParams.value
  }, `llm_${new Date().getTime()}.xlsx`);
}

function handleCach() {
  cachLlm().then(response => {
    proxy.$modal.msgSuccess("缓存成功");
  })
}

/** 是否渲染字段 */
function renderField(insert, edit) {
  return form.value.id == null ? insert : edit;
}

getList();
</script>